#include <cstdio>
#include <cstdlib> //malloc
#include <cstring> //memset
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h> //sockaddr_in
#include <arpa/inet.h>  //inet_ntop
#include <signal.h>
#include <thread>
#include <mutex>
#include <opencv2/opencv.hpp>
#include "face.h"

using namespace std;
using namespace cv;
using namespace aip;

string appid = "18003626";
string apikey = "kIGVsMnZEKqCfLfnl9op20cq";
string secretkey = "udOcOUcZ1sRVG40sHTm5x4FzjiUxmpUh";

VideoCapture cam;

Mat frame;
mutex frame_mutex;

Rect range;
mutex range_mutex;

void handle_client(int sd)
{
    char buf[BUFSIZ];

    FILE *sfp = fdopen(sd, "r+");
    if (!sfp)
    {
        perror("fdopen");
        return;
    }

    while (1)
    {
        while (fgets(buf, BUFSIZ, sfp) && strlen(buf) > 2)
        {
            //printf(buf);
        }

        if (ferror(sfp) || feof(sfp))
        {
            printf("connection closed\n");
            break;
        }

        Mat image;
        vector<unsigned char> body;
        frame_mutex.lock();
        //复制图像
        image = frame.clone();
        frame_mutex.unlock();

        range_mutex.lock();
        rectangle(image, range, CV_RGB(255, 0, 0));
        range_mutex.unlock();

        imencode(".jpg", image, body);

        fprintf(sfp, "HTTP/1.1 200 OK\r\n");
        fprintf(sfp, "Content-Type: image/jpeg\r\n");
        fprintf(sfp, "Content-Length: %zd\r\n", body.size());
        fprintf(sfp, "\r\n");
        fwrite((char *)body.data(), 1, body.size(), sfp);
    }

    fclose(sfp);
}

void capture(void)
{
    puts("camera start");

    while (1)
    {
        frame_mutex.lock();
        cam >> frame;
        frame_mutex.unlock();
        this_thread::yield();
    }
}

void mark(Mat& image, 
          double left, 
          double top, 
          double width, 
          double height, 
          int64_t rotation, 
          const Scalar& color, 
          int thickness,
          const string& text = "")
{
    //将人脸区域扩大4倍之后，以原区域的左上角作为原点进行旋转
    RotatedRect rRect = RotatedRect(Point2f(left, top), Size2f(2*width, 2*height), rotation);
    Point2f vertices[4];
    rRect.points(vertices); //获取旋转后矩形的4个顶点

    Point2f bl = (vertices[3] + vertices[0])/2; //计算旋转后的左下角（线段中点）
    Point2f tl2 = (vertices[1] + vertices[2])/2;
    Point2f tl = (bl + tl2)/2;//左上角
    Point2f tr = (vertices[2] + vertices[3])/2;//右上角
    Point2f br = vertices[3]; //右下角

    line(image, bl, tl, color, thickness, LINE_AA);
    line(image, tl, tr, color, thickness, LINE_AA);
    line(image, tr, br, color, thickness, LINE_AA);
    line(image, br, bl, color, thickness, LINE_AA);

    putText(image, text, Point(left, top), FONT_HERSHEY_DUPLEX, 1, color, thickness, LINE_AA);
}

void face_detect(Mat& snapshot)
{
    //创建人脸识别客户端
    Face client(appid, apikey, secretkey);
    vector<unsigned char> image;

    imencode(".jpg", snapshot, image);
    map<string, string> options;
    options["face_field"] = "age,beauty,gender,glasses,emotion,mask";
    options["max_face_num"] = "120";

    string base64 = base64_encode((char*)image.data(), image.size());
    Json::Value result = client.detect(base64, "BASE64", options);

    //cout << result.toStyledString() << endl;

    Json::Value face_list = result["result"]["face_list"];
    for (unsigned int i = 0; i < face_list.size(); i++)
    {
        double x = face_list[i]["location"]["left"].asDouble();
        double y = face_list[i]["location"]["top"].asDouble();
        double h = face_list[i]["location"]["height"].asDouble();
        double w = face_list[i]["location"]["width"].asDouble();
        int64_t r = face_list[i]["location"]["rotation"].asInt();
        //性别
        string gender = face_list[i]["gender"]["type"].asString();
        //颜值
        string beauty = face_list[i]["beauty"].asString();
        //情绪
        string emotion = face_list[i]["emotion"]["type"].asString();
        //年龄
        string age = face_list[i]["age"].asString();

        mark(snapshot, x, y, w, h, r, Scalar(0, 0, 255), 2, age);
        printf("face detected: gender: %s, beauty: %s, emotion: %s, age: %s\n",
               gender.c_str(), 
               beauty.c_str(),
               emotion.c_str(),
               age.c_str());
    }
    
    imwrite("output.jpg", snapshot);
}

void detect(void)
{
    CascadeClassifier classifier;
    classifier.load("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml");
    //classifier.load("/usr/share/opencv/lbpcascades/lbpcascade_frontalface.xml");
    Mat gray;
    vector<Rect> faces;

    puts("face detection start");

    while (1)
    {
        frame_mutex.lock();
        Mat snapshot = frame.clone();
        frame_mutex.unlock();
        cvtColor(snapshot, gray, COLOR_BGR2GRAY);
        equalizeHist(gray, gray);
        classifier.detectMultiScale(gray, faces, 2, 1);
        if (faces.size())
        {
            face_detect(snapshot);
        }
    }
}

int main()
{
    cam.open(0);
    cam >> frame; //make sure frame is not empty

    thread capture_thread(capture);
    thread detect_thread(detect);

    capture_thread.detach();
    detect_thread.detach();

    signal(SIGPIPE, SIG_IGN);

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);

    if (listenfd < 0)
    {
        perror("socket");
        return 1;
    }

    int opt = 1;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in saddr;
    memset(&saddr, 0, sizeof(saddr));

    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = htons(8000);
    if (bind(listenfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
    {
        perror("bind");
        return 1;
    }

    if (listen(listenfd, 64) < 0)
    {
        perror("listen");
        return 1;
    }

    puts("web server start");

    while (1)
    {
        struct sockaddr_in caddr;
        socklen_t addrlen = sizeof(caddr);
        long connfd;
        connfd = accept(listenfd, (struct sockaddr *)&caddr, &addrlen);

        char ipstr[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &caddr.sin_addr, ipstr, sizeof ipstr);
        printf("client %s connected\n", ipstr);
        if (connfd < 0)
        {
            perror("accept");
            continue;
        }

        thread client_thread(handle_client, connfd);
        client_thread.detach();
    }
}
